from flask import Blueprint, request, redirect

# 蓝图变量名request_blueprint要和下方@装饰器一致，而Blueprint()中的蓝图名称'request'是独立的
request_blueprint = Blueprint('request', __name__)


# 装饰器中的第一个参数'/CommonPost'为访问路径，下方的方法名可以纯自定义、与其他名字完全不同
@request_blueprint.route('/CommonPost', methods=['POST'])
def request_CommonPost():
    # Get the request body as a string
    body = request.data
    print(f"Request body: {body}")

    # Get the request body as a JSON dictionary
    json_data = request.get_json()
    print(f"JSON data: {json_data}")
    return f"JSON data: {json_data}"


# 装饰器中的第一个参数'/CommonGet'为访问路径，下方的方法名可以纯自定义、与其他名字完全不同
@request_blueprint.route('/CommonGet', methods=['GET'])
def request_CommonGet():
    # Get the request body as a string
    body = '"responseMsg":"访问示例成功"'
    print(f"Request body: {body}")
    return f"{body}"


# 上传文件
@request_blueprint.route('/UploadFile', methods=['POST'])
def request_UploadFile():
    # 检查是否有文件部分
    if 'file' not in request.files:
        return redirect(request.url)
    file = request.files['file']
    # 如果用户没有选择文件，浏览器也会提交一个空的文件名
    if file.filename == '':
        return redirect(request.url)
    # if file and file.filename.endswith(('.png', '.jpg', '.jpeg', '.txt', '.doc', '.docx', '.xls', '.xlsx', '.pdf', '.ppt', '.pptx', '.zip', '.rar')):
    if file:
        # 保存文件到服务器上的某个位置
        file.save('./file/'+file.filename)
        return 'File successfully uploaded!'
    else:
        return 'Invalid file type!'

    # body = {
    #     "SYS_INTER_FACE": "接口系统名",
    #     "INTER_PROC_NAME": "接口所属模块",
    #     "INTER_FACE_NAME": "/api/base/device/info",
    #     "SND_TIME": "发送时间",
    #     "SND_CON": "发送内容",
    #     "CREATE_USER_ID": "记录创建人",
    #     "CREATE_DATE": "记录创建时间",
    #     "MODIFY_USER_ID": "记录修改人",
    #     "MODIFY_DATE": "记录修改时间",
    #     "Content": {
    #         "credit_code": "企业信用代码",
    #         "id": "设备ID",
    #         "device_code": "设备编码",
    #         "device_name": "设备名称",
    #         "device_type": "设备类型",
    #         "throw_in_time": " 开始投用时间",
    #         "use_years": "设计使用年限",
    #         "last_inspect_time": "检定日期",
    #         "last_inspect_result": "检定结果",
    #         "next_inspect_time": "下次检定日期",
    #         "last_inspect_name": "最新检验人",
    #         "is_special": "是否特种设备",
    #         "last_inspect_file": "检定报告文件",
    #         "address": "设备地址",
    #         "use_status": "使用状态",
    #         "describe": "备注描述"
    #     }
    # }
    # json_string = json.dumps(body)
    # return "Received POST request.\n"+f"Request body: \n{body}"
